<template>
  <div class="assessments-container">
    <el-card class="assessments-card">
      <template #header>
        <div class="card-header">
          <span>考核方案管理</span>
          <el-button type="primary" @click="handleAdd">新增方案</el-button>
        </div>
      </template>

      <el-form :inline="true" class="search-form">
        <el-form-item label="方案名称">
          <el-input v-model="searchForm.name" placeholder="请输入方案名称" clearable />
        </el-form-item>
        <el-form-item label="状态" style="width: 250px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="draft" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="assessmentList" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="方案名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="period" label="考核周期" width="100">
          <template #default="{ row }">
            <el-tag>{{ getPeriodText(row.period) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="month" label="考核月份" width="120">
        </el-table-column>
        <el-table-column prop="department" label="考核部门" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getDepartmentName(row.department) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="200">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button 
              type="primary" 
              link 
              @click="handlePublish(row)"
              v-if="row.status === 'draft'"
            >发布</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 考核方案表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增考核方案' : '编辑考核方案'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="assessmentForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="方案名称" prop="name">
          <el-input v-model="assessmentForm.name" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="考核周期" prop="period">
          <el-select v-model="assessmentForm.period" placeholder="请选择考核周期">
            <el-option label="月度" value="monthly" />
            <el-option label="季度" value="quarterly" />
            <el-option label="年度" value="yearly" />
          </el-select>
        </el-form-item>
        <el-form-item label="考核月份" prop="month">
          <el-date-picker
            v-model="assessmentForm.month"
            type="month"
            placeholder="请选择考核月份"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="考核部门" prop="department">
          <el-tree-select
            v-model="assessmentForm.departmentIds"
            :data="departmentOptions"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            multiple
            placeholder="请选择考核部门"
          />
        </el-form-item>
        <el-form-item label="考核指标" prop="kpis">
          <el-table :data="selectedKPIs" border style="width: 100%">
            <el-table-column prop="id" width="50" label="序号" />
            <el-table-column prop="name" label="指标名称" width="120"/>
            <el-table-column prop="type" label="类型" width="120">
              <template #default="{ row }">
                <el-tag size="small">{{ getKPITypeText(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="weight" label="权重" width="200">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.weight"
                  :min="1"
                  :max="100"
                  size="small"
                  @change="handleWeightChange"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" >
              <template #default="{ row, $index }">
                <el-button type="danger" link @click="removeKPI($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="add-kpi-button">
            <el-button type="primary" link @click="showKPISelector">
              <el-icon><Plus /></el-icon> 添加指标
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="assessmentForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 指标选择器对话框 -->
    <el-dialog
      v-model="kpiSelectorVisible"
      title="选择考核指标"
      width="600px"
    >
      <el-table
        :data="availableKPIs"
        @selection-change="handleKPISelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="指标名称" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ getKPITypeText(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="默认权重" width="100">
          <template #default="{ row }">
            {{ row.weight }}%
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="kpiSelectorVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmKPISelection">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 步骤编辑器对话框 -->
    <el-dialog
      v-model="stepEditorVisible"
      :title="editingStepIndex === -1 ? '添加步骤' : '编辑步骤'"
      width="500px"
    >
      <el-form
        ref="stepFormRef"
        :model="stepForm"
        :rules="stepRules"
        label-width="80px"
      >
        <el-form-item label="步骤名称" prop="name">
          <el-input v-model="stepForm.name" placeholder="请输入步骤名称" />
        </el-form-item>
        <el-form-item label="步骤说明" prop="description">
          <el-input
            v-model="stepForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入步骤说明"
          />
        </el-form-item>
        <el-form-item label="处理人" prop="handlers">
          <el-select
            v-model="stepForm.handlers"
            multiple
            placeholder="请选择处理人"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时限(天)" prop="timeLimit">
          <el-input-number
            v-model="stepForm.timeLimit"
            :min="1"
            :max="30"
            :step="1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stepEditorVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStep">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { getAssessmentPage, getSteps, addAssessment, updateAssessment, getAssessmentKPIs, publishAssessment } from '@/api/assessments'
import { getDepartmentKPIIds, getDepartmentList } from '@/api/departments'
import { getKPIList } from '@/api/kpis'

interface Assessment {
  id: number
  name: string
  period: string
  startDate: string
  endDate: string
  department: number
  departmentName?: string
  status: string
  progress: number
  kpiIds: number[]
  process: ProcessStep[]
  remark: string
}

interface ProcessStep {
  name: string
  description: string
  handlers: number[]
  timeLimit: number
}

interface KPI {
  id: number
  name: string
  type: string
  weight: number
}

interface Department {
  id: number
  name: string
  children?: Department[]
}

interface Role {
  id: number
  name: string
}

const loading = ref(false)
const dialogVisible = ref(false)
const kpiSelectorVisible = ref(false)
const stepEditorVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref<FormInstance>()
const stepFormRef = ref<FormInstance>()

const searchForm = reactive({
  name: '',
  period: '',
  status: ''
})

const assessmentForm = reactive({
  id: 0,
  name: '',
  period: '',
  month: '',
  departmentIds: [],
  kpis: [] as KPI[],
  process: [] as ProcessStep[],
  remark: ''
})

const stepForm = reactive({
  name: '',
  description: '',
  handlers: [] as number[],
  timeLimit: 1
})

const rules = {
  name: [{ required: true, message: '请输入方案名称', trigger: 'blur' }],
  period: [{ required: true, message: '请选择考核周期', trigger: 'change' }],
  month: [{ required: true, message: '请选择考核月份', trigger: 'change' }],
  departmentIds: [{ required: true, message: '请选择考核部门', trigger: 'change' }],
  kpis: [{ required: true, message: '请选择考核指标', trigger: 'change' }]
}

const stepRules = {
  name: [{ required: true, message: '请输入步骤名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入步骤说明', trigger: 'blur' }],
  handlers: [{ required: true, message: '请选择处理人', trigger: 'change' }],
  timeLimit: [{ required: true, message: '请设置时限', trigger: 'blur' }]
}

const assessmentList = ref<Assessment[]>([])
const selectedKPIs = ref<KPI[]>([])
const availableKPIs = ref<KPI[]>([])
const departmentOptions = ref<Department[]>([])
const departmentList = ref<Department[]>([])
const roleOptions = ref<Role[]>([])
const editingStepIndex = ref(-1)

function getPeriodText(period: string) {
  const map: Record<string, string> = {
    monthly: '月度',
    quarterly: '季度',
    yearly: '年度'
  }
  return map[period] || period
}

function getStatusType(status: string) {
  const map: Record<string, string> = {
    draft: 'info',
    in_progress: 'warning',
    completed: 'success'
  }
  return map[status] || 'info'
}

function getStatusText(status: string) {
  const map: Record<string, string> = {
    draft: '草稿',
    in_progress: '进行中',
    completed: '已完成'
  }
  return map[status] || status
}

function getKPITypeText(type: string) {
  const map: Record<string, string> = {
    performance: '业绩指标',
    behavior: '行为指标',
    ability: '能力指标'
  }
  return map[type] || type
}

// 获取月份的最后一天
function getMonthEndDate(month: string): string {
  const [year, monthNum] = month.split('-').map(Number)
  const lastDay = new Date(year, monthNum, 0).getDate()
  return `${month}-${lastDay.toString().padStart(2, '0')}`
}

// 获取部门名称
function getDepartmentName(departmentId: string): string {
  // departmentId 是逗号分隔的字符串
  const departmentIds = departmentId.split(',')
  // 名称也用逗号分隔输出
  const departmentNames = departmentIds.map(id => departmentList.value.filter(dept => dept.id == Number(id))[0].name)
  return departmentNames.join(',')
}

// 加载部门列表
async function loadDepartments() {
  try {
    const response = await getDepartmentList()
    departmentList.value = response
    departmentOptions.value = buildDepartmentTree(response)
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
    departmentOptions.value = []
  }
}

function buildDepartmentTree(departments: any[]): any[] {
  const departmentMap = new Map()
  const tree: any[] = []
  
  // 首先将所有部门存入map
  departments.forEach(dept => {
    departmentMap.set(dept.id, { ...dept, children: [] })
  })
  
  // 构建树形结构
  departments.forEach(dept => {
    const node = departmentMap.get(dept.id)
    if (dept.parentId) {
      const parent = departmentMap.get(dept.parentId)
      if (parent) {
        parent.children.push(node)
      }
    } else {
      tree.push(node)
    }
  })
  
  return tree
}

async function loadAssessments() {
  loading.value = true
  try {
    const response = await getAssessmentPage({
      current: currentPage.value,
      size: pageSize.value,
      name: searchForm.name,
      period: searchForm.period,
      status: searchForm.status
    })
    
    assessmentList.value = response.records || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取考核方案列表失败:', error)
    ElMessage.error('获取考核方案列表失败')
    assessmentList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  currentPage.value = 1
  loadAssessments()
}

function handleReset() {
  Object.assign(searchForm, {
    name: '',
    period: '',
    status: ''
  })
  handleSearch()
}

function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(assessmentForm, {
    id: 0,
    name: '',
    period: '',
    month: '',
    departmentIds: [],
    kpis: [],
    process: [],
    remark: ''
  })
  selectedKPIs.value = []
}

function handleAdd() {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

async function handleEdit(row: Assessment) {
  dialogType.value = 'edit'
  // 调用接口getSteps
  const process = await getSteps(row.id)
  // 查询考核方案对应的KPI列表
  const kpis = await getAssessmentKPIs(row.id)

  selectedKPIs.value = kpis
  
  Object.assign(assessmentForm, {
    id: row.id,
    name: row.name,
    period: row.period,
    month: row.startDate ? row.startDate.substring(0, 7) : '',
    departmentIds: row.department.split(',').map(id => Number(id)),
    kpis: kpis,
    process: [...process],
    remark: row.remark
  })
  dialogVisible.value = true
}

function handleView(row: Assessment) {
  // TODO: 实现查看详情功能
  ElMessage.info('查看详情功能开发中')
}

function handlePublish(row: Assessment) {
  ElMessageBox.confirm(
    '发布后将无法修改，是否确认发布？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await publishAssessment(row.id)
        ElMessage.success('发布成功')
        loadAssessments()
      } catch (error) {
        console.error('发布失败:', error)
        ElMessage.error('发布失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消发布')
    })
}

function handleDelete(row: Assessment) {
  ElMessageBox.confirm(
    '确定要删除该考核方案吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // TODO: 实现删除功能
      ElMessage.success('删除成功')
      loadAssessments()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 将月份转换为开始日期和结束日期
    const month = assessmentForm.month
    
    const formData = {
      name: assessmentForm.name,
      period: assessmentForm.period,
      month: month,
      department: assessmentForm.departmentIds.join(','),
      kpis: assessmentForm.kpis,
      process: assessmentForm.process,
      remark: assessmentForm.remark,
      status: 'draft',
      progress: 0
    }
    
    if (dialogType.value === 'add') {
      await addAssessment(formData)
      ElMessage.success('新增成功')
    } else {
      // 编辑时需要包含departmentIds, 逗号分隔
      formData.department = assessmentForm.departmentIds.join(',')
      await updateAssessment({ ...formData, id: assessmentForm.id })
      ElMessage.success('编辑成功')
    }
    
    dialogVisible.value = false
    loadAssessments()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
  }
}

function handleSizeChange(val: number) {
  pageSize.value = val
  loadAssessments()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  loadAssessments()
}

function showKPISelector() {
  kpiSelectorVisible.value = true
}

function handleKPISelectionChange(selection: KPI[]) {
  selectedKPIs.value = selection
}

function confirmKPISelection() {
  assessmentForm.kpis = [...selectedKPIs.value]
  kpiSelectorVisible.value = false
}

function handleWeightChange() {
  const totalWeight = selectedKPIs.value.reduce((sum, kpi) => sum + kpi.weight, 0)
  if (totalWeight !== 100) {
    ElMessage.warning(`当前权重总和为${totalWeight}%，请调整至100%`)
  }
}

function removeKPI(index: number) {
  selectedKPIs.value.splice(index, 1)
  assessmentForm.kpis = [...selectedKPIs.value]
}

function handleAddStep() {
  editingStepIndex.value = -1
  Object.assign(stepForm, {
    name: '',
    description: '',
    handlers: [],
    timeLimit: 1
  })
  stepEditorVisible.value = true
}

async function confirmStep() {
  if (!stepFormRef.value) return

  try {
    await stepFormRef.value.validate()
    if (editingStepIndex.value === -1) {
      assessmentForm.process.push({ ...stepForm })
    } else {
      assessmentForm.process[editingStepIndex.value] = { ...stepForm }
    }
    stepEditorVisible.value = false
  } catch (error) {
    console.error('步骤表单验证失败:', error)
  }
}

// 加载KPI列表
async function loadKPIs() {
  try {
    const response = await getKPIList()
    availableKPIs.value = response
  } catch (error) {
    console.error('获取KPI列表失败:', error)
    ElMessage.error('获取KPI列表失败')
  }
}

onMounted(() => {
  loadDepartments()
  loadAssessments()
  loadKPIs()
})
</script>

<style scoped>
.assessments-container {
  padding: 20px;
}

.assessments-card {
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--el-fill-color-blank);
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.add-kpi-button {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.process-editor {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}
</style>